﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UdrinkWater_Project.Customer
{
    public partial class ShowOrderList : System.Web.UI.Page
    {
        NetOrderClassDataContext db = new NetOrderClassDataContext();
        string Connection = ConfigurationManager.ConnectionStrings["DB_Udrink"].ConnectionString;
        public   DateTime Order_Date_ID = DateTime.Now;
        public   string OrderID,T1,T2;

        protected void Page_Load(object sender, EventArgs e)
        {
           
            
            if (!IsPostBack && Session["TablePrice"] != null)
            {                     
                BindGrid();
            }
            if (IsPostBack && Session["TablePrice"] != null)
            {
                OrderID = Order_Date_ID.ToString("yyyy-MM-dd HH:mm:ss.fff", new System.Globalization.CultureInfo("en-US"));
                T1 = Order_Date_ID.ToString("yyyy-MM-dd", new System.Globalization.CultureInfo("en-US"));
                T2 = Order_Date_ID.ToString("HH:mm:ss.fff", new System.Globalization.CultureInfo("en-US"));
                
            }
            if (!IsPostBack && Session["TablePrice"] == null)
            {
                
                OrderID = Order_Date_ID.ToString("yyyy-MM-dd HH:mm:ss.fff", new System.Globalization.CultureInfo("en-US"));
                 T1 = Order_Date_ID.ToString("yyyy-MM-dd", new System.Globalization.CultureInfo("en-US"));
                T2 = Order_Date_ID.ToString("HH:mm:ss.fff", new System.Globalization.CultureInfo("en-US"));    
                Session["TablePrice"] = null;
                BindGrid();
            }
            
            
        }
        protected void BindGrid()
        {

            txtCustomer.Text = Session["User"].ToString();
            DataTable DetailCustomer = new DataTable();
            DetailCustomer = GetDetialCustomer(txtCustomer.Text);
            txtCustomerName.Text = DetailCustomer.Rows[0]["Prefix"].ToString() + " " +
                                   DetailCustomer.Rows[0]["Firstname"].ToString() + " " +
                                   DetailCustomer.Rows[0]["Lastname"].ToString();
            txtAdress.Text = DetailCustomer.Rows[0]["Adress"].ToString();
            ASPxComboBox1.Value = DetailCustomer.Rows[0]["PROVINCE_ID"];
            ASPxComboBox2.Value = DetailCustomer.Rows[0]["AMPHUR_ID"];
            ASPxComboBox3.Value = DetailCustomer.Rows[0]["DISTRICT_ID"];                     
             txtZipCode.Text = DetailCustomer.Rows[0]["Zipcode"].ToString();
            txtDate.Text = Order_Date_ID.ToString("dd/MM/yyyy HH:mm:ss", new System.Globalization.CultureInfo("th-TH"));
            txtShipp.Text = DateTime.Now.AddDays(3).ToString();
            GV_OrderList.DataSource = Session["TablePrice"] as DataTable;
            GV_OrderList.DataBind();
        }
        protected void btSubmit_Click(object sender, EventArgs e)
        {
            if (Session["TablePrice"] != null)
            {
                DataTable dt = new DataTable();
                dt = (DataTable)Session["TablePrice"];
                string sqltext = @"INSERT INTO [TB_Order]
                                  ([Order_Date]
                                ,[Customer_ID]
                                ,[Shipped_date]
                                ,[Delivery_Address]
                                ,[District_ID]
                                ,[Aumphur_ID]
                                ,[Province_ID]    
                                ,[Zipcode]                            
                                ,[Status_Unpaid]                              
                                ,[Status_Buy])
VALUES (@Order_Date,@Customer_ID,@Shipped_date,@Delivery_Address,@District_ID,@Aumphur_ID,@Province_ID,@Zipcode,@Status_Unpaid,@Status_Buy)";
                                   
                SqlCommand sqlcomm = new SqlCommand();
                SqlConnection sqlconn = new SqlConnection(Connection);
                sqlcomm.Connection = sqlconn;
                sqlcomm.CommandType = System.Data.CommandType.Text;
                sqlcomm.CommandText = sqltext;
                sqlcomm.Parameters.AddWithValue("@Order_Date", OrderID);
                sqlcomm.Parameters.AddWithValue("@Customer_ID", Session["User"].ToString());
                sqlcomm.Parameters.AddWithValue("@Shipped_date", DateTime.Now.AddDays(3));
                sqlcomm.Parameters.AddWithValue("@Delivery_Address", txtAdress.Text);
                sqlcomm.Parameters.AddWithValue("@District_ID", ASPxComboBox3.Value);
                sqlcomm.Parameters.AddWithValue("@Aumphur_ID", ASPxComboBox2.Value);
                sqlcomm.Parameters.AddWithValue("@Province_ID", ASPxComboBox1.Value);
                sqlcomm.Parameters.AddWithValue("@Zipcode", txtZipCode.Text);
                sqlcomm.Parameters.AddWithValue("@Status_Unpaid", 2);
                sqlcomm.Parameters.AddWithValue("@Status_Buy", 1);
                
                try
                {
                    sqlcomm.Connection.Open();
                    sqlcomm.ExecuteNonQuery();
                }
                catch (Exception)
                {
                    sqlcomm.Connection.Close();
                    sqlcomm.Connection.Dispose();
                }
                sqlcomm.Connection.Close();
                sqlcomm.Connection.Dispose();
                        
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string sqltext1 = @"INSERT INTO [TB_Orderlist]
                                            ([Order_Date]
                                            ,[Product_ID]
                                            ,[Product_Count]
                                            ,[Price]
                                            ,[Discount])                                             
                                            values
                                    (@Order_Date,@Product_ID,@Product_Count,@Price,@Discount)";
                    SqlCommand sqlcomm1 = new SqlCommand();
                    SqlConnection sqlconn1 = new SqlConnection(Connection);
                    sqlcomm1.Connection = sqlconn1;
                    sqlcomm1.CommandType = System.Data.CommandType.Text;
                    sqlcomm1.CommandText = sqltext1;
                    sqlcomm1.Parameters.AddWithValue("@Order_Date", OrderID);
                    sqlcomm1.Parameters.AddWithValue("@Product_ID", dt.Rows[i]["Goods_ID"].ToString());
                    sqlcomm1.Parameters.AddWithValue("@Product_Count", Convert.ToInt32(dt.Rows[i]["PriceNumber"].ToString()));
                    sqlcomm1.Parameters.AddWithValue("@Price", float.Parse(dt.Rows[i]["Price"].ToString()));
                    sqlcomm1.Parameters.AddWithValue("@Discount", 0);
                    try
                    {
                        sqlcomm1.Connection.Open();
                        sqlcomm1.ExecuteNonQuery();
                    }
                    catch (Exception)
                    {
                        sqlcomm1.Connection.Close();
                        sqlcomm1.Connection.Dispose();
                    }
                    sqlcomm1.Connection.Close();
                    sqlcomm1.Connection.Dispose();
                }
                Session["Date"] = T1.ToString();
                Session["Time"] = T2.ToString();
                
                Response.Redirect("BillOnline.aspx");
            }
        }
        private DataTable GetData_OrderID(string GoodID)
        {
            string sqltext = @"SELECT * FROM [TB_Product] WHERE [Product_ID] ='" + GoodID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }
        private DataTable GetDetialCustomer(string ID_Card)
        {
            string sqltext = @"SELECT        TB_Customer.ID_Card, TB_Customer.Prefix, TB_Customer.Firstname, TB_Customer.Lastname, TB_Customer.Adress, TB_Customer.PROVINCE_ID, TB_Customer.AMPHUR_ID, 
                               TB_Customer.DISTRICT_ID,TB_Customer.Zipcode
                               FROM		  TB_Customer LEFT JOIN
                         TB_Aumphur ON TB_Customer.AMPHUR_ID = TB_Aumphur.AMPHUR_ID LEFT JOIN
                         TB_District ON TB_Customer.DISTRICT_ID = TB_District.DISTRICT_ID LEFT JOIN
                         TB_Province ON TB_Customer.PROVINCE_ID = TB_Province.PROVINCE_ID 
                               WHERE [ID_Card] ='" + ID_Card + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }
        public DataTable GetData_OrderIDlist(string T1,string T2)
        {//" + Session["User"].ToString() + "
            DataTable dt = new DataTable();
            string sqltext = @"SELECT [Order_Date]
                            ,[Customer_ID]
                            ,[Shipped_date]
                            ,[Delivery_Address]
                            ,[Status]
                            ,[Employee_ID]
                             FROM [DB_Udrink].[dbo].[TB_Order]
                             WHERE [Order_Date] ='"+T1+" "+T2+"'";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
        protected void GV_OrderList_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            //if (e.Column.FieldName == "Number")
            //{
            //    e.Value = string.Format("{0}", e.ListSourceRowIndex + 1);
            //}
            if (e.Column.FieldName == "TotalRow")
            {
                int price = (int)e.GetListSourceFieldValue("Price");
                int PriceNumber = (int)e.GetListSourceFieldValue("PriceNumber");
                e.Value = price * PriceNumber;
            }
        }

        protected void GV_OrderList_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            if (e.CommandArgs.CommandName == "Cmd_Delete")
            {
                // Response.Redirect("PromotionLogin.aspx");
                string Index = e.CommandArgs.CommandArgument.ToString();
                DataTable dt = (DataTable)Session["TablePrice"];
                dt.Rows[Convert.ToInt32(Index)].Delete();
                Session["TablePrice"] = dt;
                BindGrid();
            }
        }

        protected void btCancle_Click(object sender, EventArgs e)
        {
            Session["TablePrice"] = null;
            Response.Redirect("Order.aspx");
        }

        protected void rbtChooseAddres_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rbtChooseAddres.SelectedIndex == 0)
            {
                BindGrid();
                txtAdress.ReadOnly = true; txtAdress.BackColor = HexColor("#D3E4A6");
                ASPxComboBox1.ReadOnly = true; ASPxComboBox1.BackColor = HexColor("#D3E4A6");
                ASPxComboBox2.ReadOnly = true; ASPxComboBox2.BackColor = HexColor("#D3E4A6");
                ASPxComboBox3.ReadOnly = true; ASPxComboBox3.BackColor = HexColor("#D3E4A6");
                txtZipCode.ReadOnly = true; txtZipCode.BackColor = HexColor("#D3E4A6");
            }
            else
            {
                txtAdress.ReadOnly = false; txtAdress.BackColor = System.Drawing.Color.White;
                ASPxComboBox1.ReadOnly = false; ASPxComboBox1.BackColor = System.Drawing.Color.White;
                ASPxComboBox2.ReadOnly = false; ASPxComboBox2.BackColor = System.Drawing.Color.White;
                ASPxComboBox3.ReadOnly = false; ASPxComboBox3.BackColor = System.Drawing.Color.White;
                txtZipCode.ReadOnly = false; txtZipCode.BackColor = System.Drawing.Color.White;
            }
        }
        public Color HexColor(String hex)
        {
            //remove the # at the front
            hex = hex.Replace("#", "");

            byte a = 255;
            byte r = 255;
            byte g = 255;
            byte b = 255;

            int start = 0;

            //handle ARGB strings (8 characters long)
            if (hex.Length == 8)
            {
                a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                start = 2;
            }

            //convert RGB characters to bytes
            r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
            g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
            b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);

            return Color.FromArgb(a, r, g, b);
        }
        protected void ASPxButton1_Click(object sender, EventArgs e)
        {

            Response.Redirect("Order.aspx");
        }

        protected void ASPxComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ASPxComboBox2.Text = "";
            ASPxComboBox3.Text = "";
        }

        protected void ASPxComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ASPxComboBox3.Text = "";
        }
    }
}